package com.chinatechstar.file.service.impl;

import java.io.IOException;
import java.util.*;

import com.chinatechstar.admin.entity.SysUser;
import com.chinatechstar.admin.mapper.SysUserMapper;
import com.chinatechstar.component.commons.exception.AjaxExceptionEnum;
import com.chinatechstar.component.commons.utils.CurrentUserUtils;
import com.chinatechstar.component.commons.utils.FileUtils;
import com.chinatechstar.file.dto.CurrDirFileDTO;
import com.chinatechstar.file.dto.CurrDirFileMapDTO;
import com.chinatechstar.file.dto.SysDirTreeDTO;
import com.chinatechstar.file.entity.File;
import com.chinatechstar.file.mapper.SysFileBusinessMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinatechstar.file.entity.SysFile;
import com.chinatechstar.file.mapper.SysFileMapper;
import com.chinatechstar.file.service.SysFileService;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.utils.SequenceGenerator;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 业务逻辑实现层
 */
@Service
@Transactional
public class SysFileServiceImpl implements SysFileService {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final SequenceGenerator SEQUENCE_GENERATOR = new SequenceGenerator();
    private static final String FILE_COMMAND = "file";
    private static final String DIR_COMMAND = "dir";
    private static final String FILE_UPLOAD = "upload";
    private static final String FILE_UPDATE = "update";
    private static final String FILE_RENAME = "rename";
    private static final String DIR_MKDIR = "mkdir";
    private static final String DIR_RENAME = "rename";
    private static final String COPY_COMMAND = "copy";
    private static final String MOVE_COMMAND = "move";
    private static final String EXTENSION_DIR = "dir";

    @Autowired
    private SysFileMapper sysFileMapper;
    @Autowired
    private SysFileBusinessMapper sysFileBusinessMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询所有数据
     */
    @Override
    public List<SysFile> findSysFileAll() {
        return sysFileMapper.findSysFileAll();
    }

    /**
     * 查询分页
     */
    @Override
    public Map<String, Object> findSysFileByCondition(Integer currentPage, Integer pageSize, String name, String sorter) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        if (StringUtils.isNotBlank(sorter)) {
            String sort = sorter.substring(0, sorter.lastIndexOf('_'));
            String sequence = "ascend".equals(sorter.substring(sorter.lastIndexOf('_') + 1)) ? "ASC" : "DESC";
            paramMap.put("sort", sort);
            paramMap.put("sequence", sequence);
        } else {
            paramMap.put("sort", "createTime");
            paramMap.put("sequence", "DESC");
        }
        Page<Object> page = PageHelper.startPage(currentPage, pageSize);
        List<LinkedHashMap<String, Object>> resultList = sysFileMapper.findSysFileByCondition(paramMap);
        return PaginationBuilder.buildResult(resultList, page.getTotal(), currentPage, pageSize);
    }

    /**
     * 查询导出数据列表
     */
    @Override
    public List<LinkedHashMap<String, Object>> findSysFileForExcel(Map<String, Object> paramMap) {
        return sysFileMapper.findSysFileByCondition(paramMap);
    }

    /**
     * 根据主键ID数据查询数据
     */
    @Override
    public SysFile findSysFileById(Long id) {
        return sysFileMapper.findSysFileById(id);
    }

    /**
     * 根据主键ID数组查询数据
     */
    @Override
    public List<SysFile> findSysFileByIds(Long[] ids) {
        return sysFileMapper.findSysFileByIds(ids);
    }

    /**
     * 新增
     */
    @Override
    public void insertSysFile(SysFile sysFile) {
        SysUser currUser = sysUserMapper.getUserByUsername(CurrentUserUtils.getOAuth2AuthenticationInfo().get("name"));

        sysFile.setId(SEQUENCE_GENERATOR.nextId());
        sysFile.setCreateName(currUser.getNickname());
        sysFile.setCreateUsername(currUser.getUsername());
        sysFileMapper.insertSysFile(sysFile);
        logger.info("已新增： {}", sysFile.getId());
    }

    /**
     * 批量新增
     */
    @Override
    public void insertSysFiles(List<SysFile> sysFiles) {
        SysUser currUser = sysUserMapper.getUserByUsername(CurrentUserUtils.getOAuth2AuthenticationInfo().get("name"));

        for (SysFile sysFile : sysFiles) {
            sysFile.setId(SEQUENCE_GENERATOR.nextId());
            sysFile.setCreateName(currUser.getNickname());
            sysFile.setCreateUsername(currUser.getUsername());
        }
        sysFileMapper.insertSysFiles(sysFiles);
    }

    /**
     * 复制或移动目录和文件命令
     */
    @Override
    public HashMap<String, HashMap<String, String>> copyMoveCommand(String command, Long[] fileIds, Long targetId, Long fileBusiness) {
        if (fileIds.length == 0) {
            throw new IllegalArgumentException(AjaxExceptionEnum.ID_IS_REQUIRED.getMsg());
        }
        HashMap<String, HashMap<String, String>> info = new HashMap<>(16);
        HashMap<String, String> single;

        switch (command) {
            case COPY_COMMAND:
                for (Long id : fileIds) {
                    single = FileUtils.copyCommand(id, targetId);
                    info.put(single.get("id"), single);
                }
                break;
            case MOVE_COMMAND:
                for (Long id : fileIds) {
                    single = FileUtils.moveCommand(id, targetId);
                    info.put(single.get("id"), single);
                }
                break;
        }
        return info;
    }




    /**
     * 文件或目录下载
     */
    @Override
    public void downloadCommand(Long fileId, String command, HttpServletResponse response) {
        switch (command) {
            case FILE_COMMAND:
                FileUtils.download(fileId, response);
                break;
            case DIR_COMMAND:
                break;
        }
    }

    /**
     * 目录操作
     */
    @Override
    public HashMap<String, String> dirCommand(String command, String dirName, Long fileBusiness, Long fileStorageId, Long targetId) {
        HashMap<String, String> info = new HashMap<>(16);

        switch (command) {
            case DIR_MKDIR:
                info = FileUtils.mkdirCommand(dirName, fileStorageId, targetId, fileBusiness);
                break;
            case DIR_RENAME:
                info = FileUtils.renameCommand(dirName, targetId);
                break;
            default:
                break;
        }
        return info;
    }

    /**
     * 打开目录
     */
    @Override
    public CurrDirFileMapDTO openDir(Long businessId, Long targetId, boolean isReview) {
        return FileUtils.openDirCommand(businessId, targetId, isReview);
    }

    /**
     * 搜索业务关联的文件
     */
    @Override
    public CurrDirFileMapDTO searchFile(Long businessId, String fileName, boolean isReview) {
        return FileUtils.searchFileCommand(businessId, fileName, isReview);
    }

    /**
     * 查询业务的树状结构目录
     *
     * @param businessId 业务id
     * @return SysDirTreeDTO
     */
    @Override
    public SysDirTreeDTO findDirTree(Long businessId) {
        return sysFileBusinessMapper.findDirsByFileBusiness(businessId);
    }

    /**
     * 编辑
     */
    @Override
    public void updateSysFile(SysFile sysFile) {
        sysFileMapper.updateSysFile(sysFile);
        logger.info("已编辑： {}", sysFile.getId());
    }

    /**
     * 批量编辑
     */
    @Override
    public void updateSysFiles(List<SysFile> sysFiles) {
        sysFileMapper.updateSysFiles(sysFiles);
    }

    /**
     * 删除
     */
    @Override
    public void deleteSysFileById(Long id) {
        sysFileMapper.deleteSysFileById(id);
    }

    /**
     * 批量删除
     */
    @Override
    public void deleteSysFileByIds(Long[] ids) {
        sysFileMapper.deleteSysFileByIds(ids);
    }

    /**
     * 软删除
     */
    @Override
    public void softDeleteSysFileById(Long id) {
//        SysFile sysFile = sysFileMapper.findSysFileById(id);
//        if (sysFile != null) {
//            sysFile.setSoftDelete(0);
//            sysFileMapper.updateSysFile(sysFile);
//        }

    }

    /**
     * 批量软删除
     */
    @Override
    public void softDeleteSysFileByIds(Long[] ids) {
//        List<SysFile> sysFiles = sysFileMapper.findSysFileByIds(ids);
//
//        if (sysFiles.size() > 0) {
//            for (SysFile sysFile : sysFiles) {
//                sysFile.setSoftDelete(0);
//            }
//
//            sysFileMapper.updateSysFiles(sysFiles);
//        }
    }

}
